#include <stdio.h>

// 包含数据结构定义
typedef struct {
    long id;
    char date[11];
    int type;
    char category[20];
    double amount;
    char note[50];
} FinanceRecord;

typedef FinanceRecord DataType;

// 单链表节点
typedef struct Node {
    DataType data;
    struct Node *next;
} SLNode;

// 声明函数
void addRecord(SLNode *head);
void deleteRecord(SLNode *head);
void modifyRecord(SLNode *head);
void queryById(SLNode *head);
void queryByCategory(SLNode *head);
void queryByAmountRange(SLNode *head);
void displayAll(SLNode *head);
void statistics(SLNode *head);
void sortByAmount(SLNode *head, int ascending);
void saveToFile(SLNode *head, const char *filename);
void loadFromFile(SLNode *head, const char *filename);

void displayMenu() {
    printf("\n=== 个人账务管理系统 ===\n");
    printf("1. 添加账务记录\n");
    printf("2. 删除账务记录\n");
    printf("3. 修改账务记录\n");
    printf("4. 按ID查询\n");
    printf("5. 按类别查询\n");
    printf("6. 按金额范围查询\n");
    printf("7. 显示所有记录\n");
    printf("8. 财务统计\n");
    printf("9. 按金额排序\n");
    printf("10. 保存数据\n");
    printf("11. 加载数据\n");
    printf("0. 退出系统\n");
    printf("请选择操作: ");
}

void handleMenu(SLNode *head) {
    int choice;
    char filename[100] = "finance_data.txt";
    
    // 启动时自动加载数据
    loadFromFile(head, filename);
    
    while(1) {
        displayMenu();
        if(scanf("%d", &choice) != 1) {
            printf("输入错误，请重新输入！\n");
            while(getchar() != '\n');
            continue;
        }
        
        switch(choice) {
            case 1:
                addRecord(head);
                break;
            case 2:
                deleteRecord(head);
                break;
            case 3:
                modifyRecord(head);
                break;
            case 4:
                queryById(head);
                break;
            case 5:
                queryByCategory(head);
                break;
            case 6:
                queryByAmountRange(head);
                break;
            case 7:
                displayAll(head);
                break;
            case 8:
                statistics(head);
                break;
            case 9:
                {
                    int order;
                    printf("排序方式: 1-升序 0-降序: ");
                    scanf("%d", &order);
                    sortByAmount(head, order);
                }
                break;
            case 10:
                saveToFile(head, filename);
                break;
            case 11:
                loadFromFile(head, filename);
                break;
            case 0:
                printf("感谢使用！\n");
                return;
            default:
                printf("无效选择，请重新输入！\n");
        }
    }
}